package com.azusa.ktc_user.controller;
import java.util.Map;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.azusa.ktc_user.entity.Follow;
import com.azusa.ktc_user.service.FollowService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;

/**
 * @Description tb_follow 控制器层
 * @author Azusa
 * @date 2020-10-12 18:33:31
*/
@RestController
@CrossOrigin
@RequestMapping("user/follow")
public class FollowController{

    @Autowired
    private FollowService followService;

    @Autowired
    private HttpServletRequest request;

    /**
    * 查询全部数据
    * @return
    */
    @RequestMapping(method= RequestMethod.GET)
    public Result findAll(){
        return new Result(StatusCode.SUCCESS,followService.findAll());
    }

    /**
    * 根据ID查询
    * @param id ID
    * @return
    */
    @RequestMapping(value="/{id}",method= RequestMethod.GET)
    public Result findById(@PathVariable String id){
        return new Result(StatusCode.SUCCESS,followService.findById(id));
    }

    /**
    * 分页+多条件查询
    * @param searchMap 查询条件封装
    * @param page 页码
    * @param size 页大小
    * @return 分页结果
    */
    @RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
        public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
        Page<Follow> pageList = followService.findSearch(searchMap, page, size);
        return  new Result(StatusCode.SUCCESS, new PageResult<Follow>(pageList.getTotalElements(), pageList.getContent()) );
    }

    /**
    * 根据条件查询
    * @param searchMap
    * @return
    */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(StatusCode.SUCCESS, followService.findSearch(searchMap));
    }

    /**
    * 关注某位用户
    * @param targetuser
    */
    @PutMapping("/{userId}")
    public Result add(@PathVariable("userId")String targetuser){
        String userId = (String) request.getAttribute("userId");
        followService.add(new Follow(userId,targetuser));
        return new Result(StatusCode.SUCCESS);
    }


    /**
    * 删除某位关注的用户
    * @param targetuser
    */
    @RequestMapping(value="/{id}",method= RequestMethod.DELETE)
    public Result delete(@PathVariable String targetuser){
        String userId = (String) request.getAttribute("userId");
        followService.deleteByUseridAndTargetuser(userId,targetuser);
        return new Result(StatusCode.SUCCESS);
    }

}
